package com.service;
import static com.def.GenericDef.ACTION_FLG_ADD;
import static com.def.GenericDef.ACTION_FLG_DELETE;
import static com.def.GenericDef.ACTION_FLG_INQUIRE;
import static com.def.GenericDef.ACTION_FLG_LIST_BY_PATH;
import static com.def.GenericDef.ACTION_FLG_LIST_WHOLE;
import static com.def.GenericDef.ACTION_FLG_QUERY;
import static com.def.GenericDef.ACTION_FLG_SEARCH;
import static com.def.GenericDef.ACTION_FLG_UPDATE;
import static com.def.GenericDef.E_XPBISOPE_BIS_PATH_NOT_FOUND;
import static com.def.GenericDef.E_XPBISOPE_NOT_FOUND_OPE;
import static com.def.GenericDef.PATH_FRST_OPE;
import static com.def.GenericDef.RETURN_CODE_OK;
import static com.def.GenericDef.RETURN_CODE_UNKNOWN;
import static com.def.GenericDef.RETURN_MESG_OK;
import static com.def.GenericDef._SPACE;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.dao.IBisDataDao;
import com.dao.IBisOpeDao;
import com.dao.IBisPathDao;
import com.icim.service.ICIMBaseService;
import com.model.Bis_data;
import com.model.Bis_ope;
import com.model.Bis_opeId;
import com.model.Bis_path;
import com.tx.Xpbisope.XpbisopeI;
import com.tx.Xpbisope.XpbisopeIB;
import com.tx.Xpbisope.XpbisopeO;
import com.tx.Xpbisope.XpbisopeOA;
import com.util.MqOpe;
import com.util.Util;

@Scope("prototype")
@Service("XpbisopeService")
public class XpbisopeService extends ICIMBaseService{
	private Logger logger = Logger.getLogger(XpbisopeService.class);
	@Autowired
	private XpbisopeI xpbisopeI;
	
	@Autowired
	private XpbisopeO xpbisopeO; 
	
	@Autowired
	private IBisPathDao bisPathDao;
	
	@Autowired
	private IBisOpeDao bisOpeDao;
	
	@Autowired
	private IBisDataDao bisDataDao;
	
	@Autowired
	private MqOpe mqOpe;
	
	public String subMainProc(String strInMsg) {
		logger.info("InTrx is "+ strInMsg );
		Session session = bisOpeDao.getCrSession();
		try{
			xpbisopeI = (XpbisopeI) mqOpe.inStr2Obj(strInMsg,xpbisopeI);
			char action_flg = xpbisopeI.getAction_flg().charAt(0);
			switch( action_flg ){
				case ACTION_FLG_QUERY        : xpbisopeO = queryByCondition()  ; break;   
				case ACTION_FLG_ADD          : xpbisopeO = addFnc()            ; break;
				case ACTION_FLG_UPDATE       : xpbisopeO = updateFnc()         ; break;
				case ACTION_FLG_DELETE       : xpbisopeO = deleteFnc()         ; break;
				case ACTION_FLG_LIST_WHOLE   : xpbisopeO = listAllFnc()        ; break;
				case ACTION_FLG_LIST_BY_PATH : xpbisopeO = getOpeByPATH()      ; break;
				case ACTION_FLG_INQUIRE      : xpbisopeO = getOpeByFabUsr()    ; break;
				case ACTION_FLG_SEARCH       : xpbisopeO = getOpeByFabUsr()    ; break;
				default                      : xpbisopeO = testFnc();   
			}
			if( RETURN_CODE_OK.equals(xpbisopeO.getRtn_code()) ){
				session.flush();
			}else{
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}catch(Exception ex){
			logger.error(Util.stackTraceToString(ex));
			xpbisopeO.setTrx_id("XPBISOPE");
			xpbisopeO.setType_id("O");
			xpbisopeO.setRtn_code(RETURN_CODE_UNKNOWN);
			xpbisopeO.setRtn_mesg(ex.getCause().toString());
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		}finally{
			logger.info(mqOpe.obj2Str(xpbisopeO));
		}
		return mqOpe.obj2Str(xpbisopeO);
	}
	/**
	 * 根据厂别和用户，筛选出可以操作的站点。
	 * @return
	 */
	private XpbisopeO getOpeByFabUsr() {
		String user_id;
		String opeIds="",sql = "";
		int i=0;
		XpbisopeIB iaryB = xpbisopeI.getIaryB().get(0);
		List<XpbisopeOA> oaryList = new ArrayList<XpbisopeOA>();
		List<Bis_ope> bisOpeList = new ArrayList<Bis_ope>();
		List<Bis_data> dataList = new ArrayList<Bis_data>();
		user_id = iaryB.getUser_id();
		String admin_sql = " FROM Bis_data where data_cate = 'UFUG'AND DATA_EXT = '" + user_id + "' AND EXT_1 = 'ADMIN' AND EXT_3='Y' ";
		List<Bis_data> UFUG_list = bisDataDao.find(admin_sql);
		if(UFUG_list.size()==1){
			String hql = "FROM Bis_ope order by convert(pep_lvl,UNSIGNED) ";
			bisOpeList = bisOpeDao.find(hql);
		}else{
			
			sql = " SELECT * FROM BIS_DATA A INNER JOIN BIS_DATA B ON A.EXT_1 = B.EXT_1 " +
					 " WHERE A.DATA_CATE IN ('UROP') AND A.DATA_EXT = '" + user_id + "'";
			dataList = bisDataDao.findBySQL(sql,Bis_data.class);
			for(i=0;i<dataList.size();i++){
				Bis_data bis_data = dataList.get(i);
				if(i==0){
					opeIds ="'"+bis_data.getExt_1()+"'";
				}else{
					opeIds +=",'"+bis_data.getExt_1()+"'";
				}
			}
			if(!opeIds.equals(_SPACE)){
				String opeSql = "FROM Bis_ope where ope_id in("+opeIds+")and ope_ver='00000'" +
						"order by convert(pep_lvl,UNSIGNED)";
				bisOpeList = bisOpeDao.find(opeSql);
			}
		}
		for(Bis_ope bis_ope : bisOpeList){
			XpbisopeOA oary = new XpbisopeOA();
			oary.setOpe_id(bis_ope.getId().getOpe_id());
			oary.setOpe_ver(bis_ope.getId().getOpe_ver());
			oary.setOpe_dsc(bis_ope.getOpe_dsc());
			oary.setProc_id(bis_ope.getProc_id());
			oary.setToolg_id(bis_ope.getToolg_id());
	        oary.setPep_lvl(bis_ope.getPep_lvl());
	        oary.setSwh_seq_id(bis_ope.getSwh_seq_id());
	        oary.setSwh_cnt(bis_ope.getSwh_cnt());
	        oary.setYield_chk_flg(bis_ope.getYield_chk_flg());
	        oary.setHand_over_flg(bis_ope.getHand_over_flg());
	        oary.setDept_id_data_id_fk(bis_ope.getDept_id_data_id_fk());
	        oary.setStd_ope_time(bis_ope.getStd_ope_time());
	        oary.setUp_load_id(bis_ope.getUp_load_id());
	        oary.setDn_load_id(bis_ope.getDn_load_id());
	        oaryList.add(oary);
		}
		/**
		 * 2100界面拆并箱时，需要PACK/WH两个站点。
		 */
		if(xpbisopeI.getAction_flg().equals("S")){
			if(UFUG_list.size()==1){
				XpbisopeOA oary = new XpbisopeOA();
				oary.setOpe_id("PACK");
				oary.setOpe_dsc("包装");
				oary.setOpe_ver("00000");
				oaryList.add(oary);
				XpbisopeOA oary2 = new XpbisopeOA();
				oary2.setOpe_id("WH");
				oary2.setOpe_dsc("成品");
				oary2.setOpe_ver("00000");
				oaryList.add(oary2);
			}else{
				for(i=0;i<dataList.size();i++){
					XpbisopeOA oary = new XpbisopeOA();
					Bis_data bis_data = dataList.get(i);
					if(bis_data.getExt_1().equals("PACK")){
						oary.setOpe_id("PACK");
						oary.setOpe_dsc("包装");
						oary.setOpe_ver("00000");
						oaryList.add(oary);
					}else if(bis_data.getExt_1().equals("WH")){
						oary.setOpe_id("WH");
						oary.setOpe_dsc("成品");
						oary.setOpe_ver("00000");
						oaryList.add(oary);
					}
				}
			}
			
		}
		xpbisopeO.setOary(oaryList);
		xpbisopeO.setTbl_cnt(oaryList.size());
		xpbisopeO.setRtn_code(RETURN_CODE_OK);
		xpbisopeO.setRtn_mesg(RETURN_MESG_OK);
		return xpbisopeO;
	}
	public XpbisopeO addFnc() {
		XpbisopeO  xpbisopeO = bisOpeDao.addProc(xpbisopeI);
		return xpbisopeO;
	}
	public XpbisopeO updateFnc(){
		XpbisopeO  xpbisopeO = bisOpeDao.updateProc(xpbisopeI);
		return xpbisopeO;
	}
	public XpbisopeO deleteFnc(){
		XpbisopeO  xpbisopeO = bisOpeDao.deleteProc(xpbisopeI);
		return xpbisopeO;
	}
	public XpbisopeO queryByCondition(){
		XpbisopeO  xpbisopeO = bisOpeDao.queryByCondition(xpbisopeI);
		return xpbisopeO;
	}
	public XpbisopeO listAllFnc(){
		XpbisopeO xpbisopeO = bisOpeDao.listAllFnc(xpbisopeI);
		return xpbisopeO ;
	}
	public XpbisopeO errActionFnc(){
		XpbisopeO  xpbisopeO = new XpbisopeO();
		xpbisopeO.setTrx_id("XPLSTDAT");
		xpbisopeO.setType_id("O");
		xpbisopeO.setRtn_code("0000009");
		xpbisopeO.setRtn_mesg("Invalid Action_flg");
		return xpbisopeO;
	}
	public XpbisopeO testFnc(){
		Session session = bisOpeDao.getCrSession();
    	Transaction tx = session.beginTransaction();
    	try{
    		Bis_ope bis_ope = new Bis_ope();
        	Bis_opeId id = new Bis_opeId();
        	id.setOpe_id("t005");
        	id.setOpe_ver("v01");
        	bis_ope.setId(id);
        	bis_ope.setUp_load_id("12");//长度大于2位
        	bisOpeDao.save(bis_ope);
        	session.flush();
        	xpbisopeO.setRtn_code(RETURN_CODE_OK);
        	xpbisopeO.setRtn_mesg("success");
    	}catch(Exception ex){
    		xpbisopeO.setRtn_mesg(ex.getCause().toString());//ex.getCause()会返回data too long 
    		xpbisopeO.setRtn_code(RETURN_CODE_UNKNOWN);
    		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    	}finally{
    		logger.info("=====>" + mqOpe.obj2Str(xpbisopeO) );
    	}
    	return xpbisopeO; 
	}
	/**
	 * 按照先后顺序筛选站点
	 * @return
	 */
	public XpbisopeO getOpeByPATH() {

		XpbisopeO xpbisopeO = new XpbisopeO();
		xpbisopeO.setTrx_id("XPBISOPE");
		xpbisopeO.setType_id("O");
		String pv_ope_no="";
		String sql = "FROM Bis_path where id.path_id_fk='"+ xpbisopeI.getPath_id_fk() +"' and "
	     + "id.path_ver_fk='"+ xpbisopeI.getPath_ver_fk() +"'";
        List<Bis_path> bis_pathList = new ArrayList<Bis_path>();
        bis_pathList = bisPathDao.find(sql);
	    if( bis_pathList.isEmpty()){
	    	xpbisopeO.setRtn_code(E_XPBISOPE_BIS_PATH_NOT_FOUND+"");
		    xpbisopeO.setRtn_mesg("工艺路线：[" + xpbisopeI.getPath_id_fk() + "]未找到！" );
		    return xpbisopeO;
	    }
		List<XpbisopeOA> oaryList = new ArrayList<XpbisopeOA>();
	    for(Bis_path cr_ope_no:bis_pathList ){
	    	Bis_opeId bis_opeId = new Bis_opeId();
	    	bis_opeId.setOpe_id(cr_ope_no.getCr_ope_id_fk());
	    	bis_opeId.setOpe_ver(cr_ope_no.getCr_ope_ver_fk());
	    	Bis_ope bis_ope = bisOpeDao.get(bis_opeId);
	    	if(bis_ope == null){
				xpbisopeO.setRtn_code(E_XPBISOPE_NOT_FOUND_OPE+"");
				xpbisopeO.setRtn_mesg("工艺路线：[" + xpbisopeI.getPath_id_fk() 
						+ "]中的站点：[" + cr_ope_no.getCr_ope_id_fk() + "]，信息未找到！" );
				return xpbisopeO;
	    	}
	    	if(cr_ope_no.getPv_ope_no().equals(PATH_FRST_OPE)){
	    		pv_ope_no = cr_ope_no.getId().getCr_ope_no();
	    		XpbisopeOA oary = new XpbisopeOA();
	    		oary.setOpe_no(pv_ope_no);
	    		oary.setOpe_id(bis_ope.getId().getOpe_id());
				oary.setOpe_ver(bis_ope.getId().getOpe_ver());
				oary.setOpe_dsc(bis_ope.getOpe_dsc());
				oary.setProc_id(bis_ope.getProc_id());
				oary.setToolg_id(bis_ope.getToolg_id());
				oaryList.add(oary);
				break;
	    	}
	    }
	    for(Bis_path cr_ope_no:bis_pathList ){
	    	if(cr_ope_no.getPv_ope_no().equals(PATH_FRST_OPE)){
	    		continue;
	    	}else{
	    		for(int i=0;i<bis_pathList.size();i++){
	    			Bis_path ope_no = bis_pathList.get(i);
	    			if(ope_no.getPv_ope_no().trim().equals(pv_ope_no.trim())){
	    				Bis_opeId bis_opeId = new Bis_opeId();
	    		    	bis_opeId.setOpe_id(ope_no.getCr_ope_id_fk());
	    		    	bis_opeId.setOpe_ver(ope_no.getCr_ope_ver_fk());
	    		    	Bis_ope bis_ope = bisOpeDao.get(bis_opeId);
	    		    	if(bis_ope == null){
	    					xpbisopeO.setRtn_code(E_XPBISOPE_NOT_FOUND_OPE+"");
	    					xpbisopeO.setRtn_mesg("工艺路线：[" + xpbisopeI.getPath_id_fk() 
	    							+ "]中的站点：[" + cr_ope_no.getCr_ope_id_fk() + "]，信息未找到！" );
	    					return xpbisopeO;
	    		    	}
		    			pv_ope_no = ope_no.getId().getCr_ope_no();
			    		XpbisopeOA oary = new XpbisopeOA();
			    		oary.setOpe_no(pv_ope_no);
			    		oary.setOpe_id(bis_ope.getId().getOpe_id());
						oary.setOpe_ver(bis_ope.getId().getOpe_ver());
						oary.setProc_id(bis_ope.getProc_id());
						oary.setOpe_dsc(bis_ope.getOpe_dsc());
						oary.setToolg_id(bis_ope.getToolg_id());
						oaryList.add(oary);
						break;
		    		}
	    		}
	    		
	    	}
	    	
	    }
		xpbisopeO.setOary(oaryList);
		xpbisopeO.setTbl_cnt(oaryList.size());
		xpbisopeO.setRtn_code(RETURN_CODE_OK);
		xpbisopeO.setRtn_mesg("success");
		return xpbisopeO;
	
	}
	
}
